<script setup lang="ts">
import { useMessageStore } from '@/stores/messageStore'
import { useCurrActStroe } from '@/stores/currActStore'
import { storeToRefs } from 'pinia'
import { watch, nextTick, ref, onMounted } from 'vue'

const timeRef = ref()

const article = ref<HTMLElement | null>()
const { currUser } = storeToRefs(useCurrActStroe())
const { logsData, userTarget } = storeToRefs(useMessageStore())

const date = new Date().toLocaleDateString()
watch(
  () => {
    if (logsData.value[date]) {
      return logsData.value[date].length
    } else {
      logsData.value[date] = []
      return logsData.value[date].length
    }
  },
  async () => {
    if (article.value) {
      await nextTick()
      article.value.scrollTo({ top: article.value.scrollHeight, behavior: 'smooth' })
    }
  }
)

// const { assignLogsData } = useMessageStore()
function showUserMsg(id: string) {
  // 查询用户数据
  // 调用组件显示
}
onMounted(() => {
  if (article.value) {
    article.value.scrollTo({ top: article.value.scrollHeight, behavior: 'smooth' })
  }
})
</script>

<template>
  <article ref="article">
    <div v-for="[date, log] in Object.entries(logsData)" :key="date">
      <p class="msg-date">{{ date }}</p>
      <section
        v-for="(item, index) in log"
        :key="item.id"
        :class="{ left: item.id !== currUser.id, right: item.id === currUser.id }"
      >
        <img
          class="user-img"
          :src="item.id === currUser.id ? currUser.img : userTarget.img"
          alt=""
          @click="showUserMsg(item.id)"
        />
        <p
          contenteditable="true"
          class="msg-content"
          @keydown.prevent
          @paste.prevent
          @mouseenter="timeRef = index"
          @mouseleave="timeRef = log.length - 1"
          v-html="item.content"
        ></p>
        <span class="msg-time" v-show="timeRef === index || index === log.length - 1">{{
          item.time
        }}</span>
      </section>
    </div>
  </article>
</template>

<style scoped>
article {
  display: grid;
  gap: 10px;
  max-height: 504px;
  scrollbar-width: none;
  overflow-y: scroll;
}
section {
  margin: 10px;
}
.left {
  display: flex;
}
.right {
  display: flex;
  flex-direction: row-reverse;
}
.user-img {
  width: 42px;
  height: 42px;
  align-self: auto;
  border-radius: var(--radius);
}
.msg-content {
  outline: none;
  font-size: 16px;
  max-width: 70%;
  margin: 0 8px;
  padding: 10px;
  border-radius: var(--radius);
  background-color: var(--color2);
  color: var(--color3);
}
.msg-time,
.msg-date {
  text-align: center;
  color: var(--color3);
  align-self: flex-end;
  font-size: 14px;
}
</style>
